package net.youdi.gateway.handler.request;

import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.youdi.gateway.handler.SensitiveCacheHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collection;
import java.util.Map;

/**
 * @author: scl
 * @date: 2020-07-23 14:00
 * @description
 */
@Component
public class SensitiveRequestBodyHandler implements RequestBodyHandler {

    private final ObjectMapper objectMapper;

    public SensitiveRequestBodyHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(),true);
    }

    @Override
    public String handler(ServerWebExchange exchange, String body) {
        try {
            Map map = objectMapper.readValue(body, Map.class);

            Collection<String> sensitives = (Collection<String>) map.get(SensitiveCacheHandler.SENSITIVE_KEY);
            if (sensitives != null && !sensitives.isEmpty()){
                for (String sensitive : sensitives) {
                    body = body.replace("\""+sensitive+"\"","null");
                }
            }
        } catch (Exception e) {
        }
        return body;
    }
}
